import { Card, Form, Input, Select, Button, Divider, Table, Space, Upload, Row, Col, Modal } from '@/utils/antd-imports';
import { PlusOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import employeeApi from '@/api/employeeApi';



import InputNumber from 'antd/es/input-number';









import DatePicker from 'antd/es/date-picker';

import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

// 模拟数据
const mockApprovalTemplates = [
  { id: 1, name: '标准项目审批流程', version: 'v1.0' },
  { id: 2, name: '紧急项目审批流程', version: 'v1.2' }
];

// 人员类型选项
const personnelTypes = [
  { value: 'company_employee', label: '公司自由人' },
  { value: 'outsourcing', label: '外协人员' },
  { value: 'formal', label: '正式工' },
  { value: 'temporary', label: '临时工' }
];

// 单价类型选项
const priceTypes = [
  { value: 'hour', label: '时' },
  { value: 'day', label: '日' },
  { value: 'month', label: '月' }
];

const ContractStep = ({ form, initialValues, onValuesChange }) => {
  const [contractPersonnel, setContractPersonnel] = useState([]);
  const [addPersonVisible, setAddPersonVisible] = useState(false);
  const [editPersonVisible, setEditPersonVisible] = useState(false);
  const [currentEditRecord, setCurrentEditRecord] = useState(null);
  const [personForm] = Form.useForm();
  const [employeeSearch, setEmployeeSearch] = useState('');
  const [employees, setEmployees] = useState([]);
  const [loadingEmployees, setLoadingEmployees] = useState(false);

  // 加载员工数据
  const loadEmployees = async () => {
    try {
      setLoadingEmployees(true);
      const response = await employeeApi.getAllActiveEmployees();
      if (response.data) {
        setEmployees(response.data);
      }
    } catch (error) {
      console.error('加载员工数据失败:', error);
    } finally {
      setLoadingEmployees(false);
    }
  };

  // 组件挂载时加载员工数据
  useEffect(() => {
    loadEmployees();
  }, []);

  // 监听initialValues变化，初始化合同人员列表
  useEffect(() => {
    if (initialValues && initialValues.contractPersonnel && initialValues.contractPersonnel.length > 0) {
      setContractPersonnel(initialValues.contractPersonnel);
    }
  }, [initialValues]);

  // 监听表单值变化，同步初始化合同人员列表（仅首次加载）
  const [hasInitialized, setHasInitialized] = useState(false);
  useEffect(() => {
    if (!hasInitialized) {
      const formValues = form.getFieldsValue();
      if (formValues && formValues.contractPersonnel && formValues.contractPersonnel.length > 0) {
        setContractPersonnel(formValues.contractPersonnel);
        setHasInitialized(true);
      }
    }
  }, [form, hasInitialized]);

  // 合同人员表格列定义
  const contractPersonnelColumns = [
    {
      title: '岗位名称',
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: '姓名',
      dataIndex: 'employee',
      key: 'employee',
      render: (employee, record) => (
        <Select
          showSearch
          value={employee}
          placeholder="选择人员"
          style={{ width: '100%' }}
          loading={loadingEmployees}
          onSearch={setEmployeeSearch}
          onChange={(value) => handleEmployeeChange(value, record.id)}
          filterOption={false}
          notFoundContent={loadingEmployees ? '加载中...' : '暂无数据'}
        >
          {employees
            .filter(emp => 
              emp.name?.includes(employeeSearch) || 
              emp.employeeCode?.includes(employeeSearch)
            )
            .map(emp => (
              <Option key={`contract-${emp.id}`} value={emp.id}>
                {emp.name} ({emp.employeeCode})
              </Option>
            ))
          }
        </Select>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text) => personnelTypes.find(t => t.value === text)?.label || text,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      render: (text) => text || '-',
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      key: 'endDate',
      render: (text) => text || '-',
    },
    {
      title: '单价(元)',
      dataIndex: 'price',
      key: 'price',
      render: (text) => text || '-',
    },
    {
      title: '单价类型',
      dataIndex: 'priceType',
      key: 'priceType',
      render: (text) => priceTypes.find(t => t.value === text)?.label || text,
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      render: (text) => text || '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" size="small" onClick={() => handleEditPersonnel(record)}>编辑</Button>
          {!record.isExisting && (
            <Button type="link" size="small" danger onClick={() => handleRemovePersonnel(record.id)}>删除</Button>
          )}
        </Space>
      ),
    },
  ];

  // 添加合同人员
  const handleAddContractPersonnel = () => {
    setAddPersonVisible(true);
    personForm.resetFields();
  };

  // 编辑合同人员
  const handleEditPersonnel = (record) => {
    setCurrentEditRecord(record);
    setEditPersonVisible(true);
    
    // 设置表单初始值
    personForm.setFieldsValue({
      ...record,
      startDate: record.startDate ? moment(record.startDate) : null,
      endDate: record.endDate ? moment(record.endDate) : null
    });
  };

  // 移除合同人员
  const handleRemovePersonnel = (id) => {
    setContractPersonnel(prev => prev.filter(person => person.id !== id));
  };

  // 确认添加人员
  const handleConfirmAddPersonnel = async () => {
    try {
      const values = await personForm.validateFields();
      
      const newPerson = {
        id: Date.now(), // 使用时间戳作为临时ID
        ...values,
        startDate: values.startDate ? values.startDate.format('YYYY-MM-DD') : null,
        endDate: values.endDate ? values.endDate.format('YYYY-MM-DD') : null,
        employee: null, // 初始时不选择人员
        type: null,
        department: null
      };
      
      setContractPersonnel(prev => [...prev, newPerson]);
      setAddPersonVisible(false);
      personForm.resetFields();
    } catch (error) {
      console.error('添加人员失败:', error);
    }
  };

  // 确认编辑人员
  const handleConfirmEditPersonnel = async () => {
    try {
      const values = await personForm.validateFields();
      
      const updatedPerson = {
        ...currentEditRecord,
        ...values,
        startDate: values.startDate ? values.startDate.format('YYYY-MM-DD') : null,
        endDate: values.endDate ? values.endDate.format('YYYY-MM-DD') : null
      };
      
      setContractPersonnel(prev => 
        prev.map(person => 
          person.id === currentEditRecord.id ? updatedPerson : person
        )
      );
      
      setEditPersonVisible(false);
      setCurrentEditRecord(null);
      personForm.resetFields();
    } catch (error) {
      console.error('编辑人员失败:', error);
    }
  };

  // 处理人员选择变化
  const handleEmployeeChange = (employeeId, recordId) => {
    const selectedEmployee = employees.find(emp => emp.id === employeeId);
    if (!selectedEmployee) return;

    setContractPersonnel(prev => 
      prev.map(person => 
        person.id === recordId 
          ? { 
              ...person, 
              employee: selectedEmployee.id,
              type: selectedEmployee.employeeType || 'formal',
              department: selectedEmployee.department
            } 
          : person
      )
    );
  };

  // 监听合同人员变化，同步到表单
  useEffect(() => {
    if (onValuesChange) {
      const currentFormValues = form.getFieldsValue();
      onValuesChange({}, {
        ...currentFormValues,
        contractPersonnel: contractPersonnel
      });
    }
  }, [contractPersonnel, form, onValuesChange]);

  return (
    <Card title="合同与人员配置" style={{ marginTop: 16 }}>
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        onValuesChange={onValuesChange}
      >
        {/* 合同信息区域 */}
        <Divider orientation="left">合同信息</Divider>
        
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="contractNumber"
              label="合同编号"
            >
              <Input placeholder="请输入合同编号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="contractAmount"
              label="合同金额（元）"
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                precision={2}
                placeholder="请输入合同金额"
              />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item name="contractRemarks" label="合同备注">
          <TextArea rows={3} placeholder="请输入合同备注信息" />
        </Form.Item>

        <Form.Item name="contractAttachment" label="合同附件">
          <Upload
            multiple
            beforeUpload={(file) => {
              // 阻止自动上传，我们将在完成立项时统一处理
              return false;
            }}
            onChange={(info) => {
              // 更新表单值
              const fileList = info.fileList.map(file => ({
                uid: file.uid,
                name: file.name,
                status: file.status,
                originFileObj: file.originFileObj
              }));
              form.setFieldValue('contractAttachment', fileList);
            }}
            fileList={form.getFieldValue('contractAttachment') || []}
          >
            <Button icon={<PlusOutlined />}>选择文件</Button>
          </Upload>
        </Form.Item>

        {/* 合同人员管理区域 */}
        <Divider orientation="left">
          合同人员管理
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            size="small" 
            style={{ marginLeft: 16 }}
            onClick={handleAddContractPersonnel}
          >
            添加岗位
          </Button>
        </Divider>

        <Table
          columns={contractPersonnelColumns}
          dataSource={contractPersonnel}
          pagination={false}
          locale={{ emptyText: '暂无合同人员配置，请点击上方按钮添加' }}
          rowKey="id"
        />
      </Form>

      {/* 添加人员弹窗 */}
      <Modal
        title="添加合同岗位"
        visible={addPersonVisible}
        width={600}
        onCancel={() => {
          setAddPersonVisible(false);
          personForm.resetFields();
        }}
        onOk={handleConfirmAddPersonnel}
        okText="确认添加"
        cancelText="取消"
      >
        <Form
          form={personForm}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="position"
                label="岗位名称"
                rules={[{ required: true, message: '请输入岗位名称' }]}
              >
                <Input placeholder="请输入岗位名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startDate"
                label="开始时间"
                rules={[{ required: true, message: '请选择开始时间' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endDate"
                label="结束时间"
                rules={[{ required: true, message: '请选择结束时间' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="单价(元)"
                rules={[{ required: true, message: '请输入单价' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  precision={2}
                  placeholder="请输入单价"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="priceType"
                label="单价类型"
                rules={[{ required: true, message: '请选择单价类型' }]}
              >
                <Select placeholder="请选择单价类型">
                  {priceTypes.map(type => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="contactPerson"
            label="对接人"
          >
            <Input placeholder="请输入对接人姓名" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑人员弹窗 */}
      <Modal
        title="编辑合同岗位"
        visible={editPersonVisible}
        width={600}
        onCancel={() => {
          setEditPersonVisible(false);
          setCurrentEditRecord(null);
          personForm.resetFields();
        }}
        onOk={handleConfirmEditPersonnel}
        okText="确认修改"
        cancelText="取消"
      >
        <Form
          form={personForm}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="position"
                label="岗位名称"
                rules={[{ required: true, message: '请输入岗位名称' }]}
              >
                <Input placeholder="请输入岗位名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startDate"
                label="开始时间"
                rules={[{ required: true, message: '请选择开始时间' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endDate"
                label="结束时间"
                rules={[{ required: true, message: '请选择结束时间' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="单价(元)"
                rules={[{ required: true, message: '请输入单价' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  precision={2}
                  placeholder="请输入单价"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="priceType"
                label="单价类型"
                rules={[{ required: true, message: '请选择单价类型' }]}
              >
                <Select placeholder="请选择单价类型">
                  {priceTypes.map(type => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="contactPerson"
            label="对接人"
          >
            <Input placeholder="请输入对接人姓名" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default ContractStep;